/* CookieImpl.java
 *
 * Author:	Malcolm Staudacher
 * Date:	Oct 22, 2008
 *
 */

package corbacookie.Cookie;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Random;
import java.util.Vector;
import javax.naming.Context;
import javax.rmi.PortableRemoteObject;
import org.omg.CORBA.ContextList;
import org.omg.CORBA.DomainManager;
import org.omg.CORBA.ExceptionList;
import org.omg.CORBA.NVList;
import org.omg.CORBA.NamedValue;
import org.omg.CORBA.ORB;
import org.omg.CORBA.Policy;
import org.omg.CORBA.Request;
import org.omg.CORBA.SetOverrideType;
import org.omg.CORBA.SystemException;
import org.omg.CORBA.portable.InputStream;
import org.omg.CORBA.portable.OutputStream;
import org.omg.CORBA.portable.ResponseHandler;
import org.omg.PortableServer.POA;

public class CookieImpl extends  cookieserverPOA {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	BufferedReader m_in;
	Vector<String> m_entries;
	private ORB m_orb;


	public void setORB(ORB orb) {
		m_orb = orb;
	}


	public CookieImpl() throws RemoteException {
		m_entries = new Vector<String>();

		try {
			m_in = new BufferedReader(new FileReader("fortunes.txt"));
		} catch (FileNotFoundException e) {
			System.out.println("Could not open File Reader");
			e.printStackTrace();
		}

		parseFile();
	}


	private void parseFile() {
		StringBuffer entry = new StringBuffer();
		String line = new String();
		int ln = 0;

		if (m_in != null) {

			while (line != null) {

				try {
					line = m_in.readLine();

					if (line != null && !line.contains("%")) {
						entry.append(line);
					} else {
						m_entries.add(new String(entry + "\n"));
						entry = new StringBuffer();
					}

				} catch (IOException e) {
					System.out.println("Error while reading file");
					e.printStackTrace();
				}

			}

		}

	}


	public String printCookie() {
		Random rand = new Random();
		int random = rand.nextInt(m_entries.size());

		return m_entries.elementAt(random);
	}


	public String printCookieNum(int i) {

		if (i < m_entries.size() && i >= 0) {
			return m_entries.elementAt(i);
		}

		return null;
	}


	public void shutdown() {
		m_orb.shutdown(false);
	}



}
